<template>
    <base-breadcrumb :title="$route.meta.title">
        <a-row :gutter="10" class="page-height">
            <a-col :span="4">
                <a-card class="page-height-tree tree-container">
                    <!-- 项目列表 -->
                    <PermissionTreeOrganization :showPermission="false" @select="handleSelect" />
                </a-card>
            </a-col>
            <a-col :span="20" class="page-height-list-wrapper">
                <searchData :search-data="searchArr" @search="search" />
                <a-card :bordered="false"  class="page-height-list">
                    <list-table
                        ref="table"
                        class="export-table"
                        :loading="loading"
                        :columns="columns"
                        :outSelectedRowKeys.sync="selectedRowKeys"
                        :request="loadData"
                        :start-index="0"
                        :statistics-config="{ use: true, statistics, temp }"
                        :export-config="{ use: true }"
                        :export-config-text="{ select: '导出选中', all: '导出全部' }"
                        :exportPermission="{select: 'qm_064_aexp_09',all: 'qm_064_sexp_08'}"
                        @exportSelect="(data)=>exportFile('checked', '项目计量设备台账列表-导出选中', data)"
                        @exportAll="exportFile('all', '项目计量设备台账列表-导出全部')"
                    >
                        <template slot="prefix">
                            <a-button
                                v-if="hideBuquBtn()"
                                v-btn-Permission="'qm_064_add_01'"
                                :disabled="selectOptions.tageCode !== 'PD'"
                                type="primary"
                                icon="plus"
                                @click="handleAdd_Edit(2)"
                            >
                                新增
                            </a-button>
                        </template>
                        <span slot="serial" slot-scope="text, record, index">{{ index + 1 }}</span>
                        <!-- 设备状态 -->
                        <template slot="statusCode" slot-scope="text, record">
                            <status-display :status-code="record.statusCode" is-approval />
                        </template>
                        <div slot="action" slot-scope="text, record">
                            <MoreButton>
                            <a v-btn-permission="'qm_064_loo_03'" @click="handleAdd_Edit(0, record)">查看</a>
                            <a v-if="record.mdBelongTo === 'SUB' && record.mdStatus === '1' && hideBuquBtn()" v-btn-permission="'qm_064_edi_02'" @click="handleAdd_Edit(1, record)">
                              编辑
                            </a>
                            <a v-if="record.mdBelongTo === 'OWN' && record.mdStatus === '1' && record.appraisalStatus === '0' && hideBuquBtn()" v-btn-permission="'qm_064_pro_05'" @click="handleOperateBtn(record, 1)">发放</a>
                            <a v-if="record.mdBelongTo === 'OWN' && record.mdStatus === '3' && hideBuquBtn()" v-btn-permission="'qm_064_tak_06'" @click="handleOperateBtn(record, 2)">收回</a>
                            <a v-if="record.mdBelongTo === 'SUB' && record.mdStatus === '1' && hideBuquBtn()" v-btn-permission="'qm_064_wal_07'" @click="handleOperateBtn(record, 3)">退场</a>
                            <a v-if="record.mdStatus === '0' || record.mdStatus === '1' || record.mdStatus === '3' && hideBuquBtn()" v-btn-permission="'qm_064_doc_04'" @click="handleOperateBtn(record, 4)">检定</a>
                            </MoreButton>
                        </div>
                    </list-table>
                </a-card>
            </a-col>
        </a-row>
        <equipment-modal ref="equipmentModal" :modalData="modalData" @handle-table-refresh="handleTableRefresh"></equipment-modal>
    </base-breadcrumb>
</template>

<script>
import PermissionTreeOrganization from '@/components/businessComponents/PermissionTreeOrganization'
import { getList, getStatisticsData, exportFile, queryReceiverInfo, equipmentVerification } from '@/api/quality/projectMeterageEquipmentAccount'
import StatusDisplay from '@/components/StatusDisplay'
import BasePage from '@/views/basePage'
import { equipmentStatusArr, checkStatusArr, equipmentBelongToArr} from '@/views/quality/equipmentManagement/constant/dictionary.js'
import EquipmentModal from './components/equipmentModal.vue'
import { grantModalData, recoveryModalData, exitModalData, verificationModal } from './components/equipmentModal.js'
import dataFilter from '@/views/quality/equipmentManagement/constant/dataFilter.js'
import handleDownload from '@/views/quality/equipmentManagement/constant/downloadFile.js'
import moment from 'moment';

export default {
    extends: new BasePage(),
    name: 'a' + Date.now(),
    components: {
        PermissionTreeOrganization,
        StatusDisplay,
        EquipmentModal
    },

    data() {
        return {
            selectedKeys: [], // 选中节点
            selectOptions: {}, // 选中节点对象
            queryParams: {},
            loading: false,
            columns: [
                {
                    title: '序号',
                    width: '65px',
                    scopedSlots: { customRender: 'serial' }
                },
                {
                    title: '设备编号',
                    width: '160px',
                    dataIndex: 'mdCode'
                },
                {
                    title: '设备名称',
                    width: '120px',
                    dataIndex: 'mdName'
                },
                {
                    title: '规格型号',
                    width: '120px',
                    dataIndex: 'specificationModel'
                },
                {
                    title: '设备归属',
                    width: '100px',
                    dataIndex: 'mdBelongTo',
                    customRender(text) {
                        return text === 'OWN' ? '自有' : '分包'
                    }
                },
                {
                    title: '进场时间',
                    width: '100px',
                    dataIndex: 'inProjectTime',
                    customRender: (text) => {
                        return text&&moment(text).locale('zh-cn').format('YYYY-MM-DD')
                    }
                },
                {
                    title: '退场时间',
                    width: '100px',
                    dataIndex: 'outProjectTime',
                    customRender: (text) => {
                        return text&&moment(text).locale('zh-cn').format('YYYY-MM-DD')
                    }
                },
                {
                    title: '设备状态',
                    width: '100px',
                    dataIndex: 'mdStatus',
                    customRender: (text) => {
                        return equipmentStatusArr.find(item => item.value === text)?.label
                    }
                },
                {
                    title: '检定状态',
                    width: '100px',
                    dataIndex: 'appraisalStatus',
                    customRender(text) {
                        return text === '0' ? '合格' : '不合格'
                    }
                },
                {
                    title: '操作',
                    dataIndex: 'action',
                    align: 'center',
                    scopedSlots: { customRender: 'action' }
                }
            ],
            loadData: (parameter) => {
                let { pageNo, pageSize } = parameter;
                let params = {
                    pageNum: pageNo,
                    pageSize
                };
                this.loading = true;
                const requestParameters = Object.assign({}, params,{param: this.setQueryParam()})
                this.getStatistics(this.setQueryParam())
                return getList(requestParameters).then((res) => {
                    this.loading = false;
                    if (res.code === '0') {
                        return { code: 200, data: res.data?.list, totalSize: res.data?.total }
                    }
                }).catch((err) => {
                    this.loading = false;
                })
            },
            searchArr: [
                // 搜索框
                {
                    name: '设备名称',
                    value: 'mdInfoName',
                    type: 'input'
                },
                {
                    name: '规格型号',
                    value: 'mdModelName',
                    type: 'input'
                },
                {
                    name: '设备编号',
                    value: 'mdCode',
                    type: 'input'
                },
                {
                    name: '检定状态',
                    value: 'appraisalStatus',
                    type: 'select',
                    data: checkStatusArr
                },
                {
                    name: '设备归属',
                    value: 'mdBelongTo',
                    type: 'select',
                    data: equipmentBelongToArr
                },
                {
                    name: '设备状态',
                    value: 'mdStatus',
                    type: 'select',
                    data: dataFilter(equipmentStatusArr, ['1','2','3','4','5'])
                },
            ],
            modalData: {},
            selectedRowKeys: [],
            statistics: {},
            temp: () => {
                return (
                <span>
                    自有设备：<span class="totalNum">{this.statistics.ownCount || 0}个</span>,
                    分包设备：<span class="totalNum">{this.statistics.subCount || 0}个</span>,
                    项目闲置：<span class="totalNum">{this.statistics.projectFreeCount || 0}个</span>,
                    使用中：<span class="totalNum">{this.statistics.useCount || 0}个</span>,
                    归还中：<span class="totalNum">{this.statistics.returnCount || 0}个</span>,
                    调拨中：<span class="totalNum">{this.statistics.transferCount || 0}个</span>,
                    退场：<span class="totalNum">{this.statistics.exitCount || 0}个</span>,
                    检定合格：<span class="totalNum">{this.statistics.qualifiedCount || 0}个</span>,
                    检定不合格：<span class="totalNum">{this.statistics.unqualifiedCount || 0}个</span>
                </span>
                )
            }
        }
    },
    methods: {
        // 导出Excel
        exportFile(tag, name, data) {
            let params = this.setQueryParam()
            if (tag === 'checked') {
                const transferIdList = data.map(item => item.id)
                let params = this.setQueryParam()
                params.ids = transferIdList
            } else {
                delete params.ids
            }
            handleDownload(exportFile, params, name)
        },
        // 设置查询参数
        setQueryParam() {
            const searchQuery = {}
            if (this.selectOptions.projectId) {
                searchQuery.projectSet = this.selectOptions.projectId  ? [this.selectOptions.projectId] : []
            } else if (this.selectOptions.orgId) {
                searchQuery.orgSet = [this.selectOptions.orgId]
            } else {
                delete searchQuery.orgSet
                delete searchQuery.projectSet
            }
            this.queryParams.searchQuery = searchQuery
            return this.queryParams
        },
        // 发放、收回、退场、检定（1，2，3，4）
        async handleOperateBtn(row, tag) {
            if(tag === 1) {
              this.modalData = grantModalData
            } else if (tag === 2) {
              this.modalData = recoveryModalData
            } else if  (tag === 3) {
              this.modalData = exitModalData
            } else {
              this.modalData = verificationModal
              this.modalData.api = equipmentVerification
            }
            this.modalData.form = row
            await this.queryReceiverInfo(tag)
            this.$refs.equipmentModal.toggleVisible()
        },
        // 收回时获取领用人信息
        async queryReceiverInfo(tag) {
            if (tag === 2) {
                let res = await queryReceiverInfo({mdProjectId: this.modalData?.form?.id})
                if (res.data) {
                    this.modalData.form = Object.assign({}, this.modalData.form, res.data)
                }
            }
        },
        // 获取统计数据
        getStatistics(params) {
            getStatisticsData(params).then((res) => {
                this.statistics = res.data
            })
        },
        // 刷新表格
        handleTableRefresh() {
            this.$refs.table.refresh(true)
        },
        handleSelect(node) {
            this.selectOptions = node
            this.search()
        },
        search(values) {
            this.queryParams = values || {}
            this.$refs.table.refresh(true)
        },
        // 新增、编辑、详情（2，1，0）
        handleAdd_Edit(editModel, row) {
            const query = {
                id: row?.id,
                editModel,
            }
            if (editModel === 2) {
                query.projectName = this.selectOptions.projectName
                query.projectId = this.selectOptions.projectId
                query.orgId = this.selectOptions.orgId
                query.branchCompanyId = this.selectOptions.parentId
            }
            if (editModel === 0) {
                query.mdOwnId = row.mdOwnId
                query.projectId = row.projectId
            }
            this.$router.push({
                path: '/quality/equipmentManagement/projectMeterageEquipmentAccountInfo',
                query
            })
        },
    }
}
</script>